dofile (getScriptPath() .. "\\..\\processor\\processor.lua")
dofile (getScriptPath() .. "\\..\\processor\\watchdog.lua")
dofile (getScriptPath() .. "\\..\\processor\\notify.lua")
dofile (getScriptPath() .. "\\..\\processor\\log.lua")

dofile (getScriptPath() .. "\\..\\lib\\delta.lua")
dofile (getScriptPath() .. "\\..\\lib\\index.lua")

script_name = string.gsub(string.gsub(debug.getinfo(1).short_src, "%.[^%.]*$", ""), "^.*[\\/]", "")

update_timer = 2000

processor:AddInit(function()
	--processor:SetTimer(2500)
end)

processor:AddInit(function(t)
	client_code = lib:GetUser()
	if not client_code then return true end
	
	script_id = client_code .. "#" .. script_name
	log_file = lib.path.log .. script_id .. ".log"
	
	processor:InitLog(log_file)
	processor:InitWatchdog(script_id)
end)

processor:AddInit(function()
	processor:log("loading instruments")
	local list = lib:LoadQuotes(lib.path.init .. "quotes.txt", nil, nil, lib.path.init .. "load_quotes.txt")
	if list then
		for i, v in ipairs(list) do
			delta:load(v.sec_code)
		end
		processor:log(#list .. " loaded")
	else
		processor:log("instruments loading error")
	end
	processor:log("loading trades")
	--message(lib:toline(lib:GetPositions()))
end)

processor:AddTimer(function()
	if update_timer then
		if not delta:save(update_timer) then
			processor:log(delta.table_index)
			return true
		end
		processor:log(delta.table_index .. " loaded")
		update_timer = nil
		table.sinsert(delta.OnM1, NotifyDelta)
	end
end)

function NotifyDelta(dd)
	--processor:log(lib:tostring(dd))
	if dd.signal_long or dd.signal_short then
		local count = delta:GetSignalCount(dd.sec_code)
		--message("NotifyDelta " .. dd.sec_code .. " " .. count)
		if count > 2 and orders:GetInstrumentPosition(dd.sec_code) == 0 then
			return
		end
		
		local str
		
		if dd.signal_long and dd.signal_long ~= 1 or dd.signal_short and dd.signal_short ~= -1 then
			str = string.format("%s DELTA %.1f", dd.sec_code, dd.trades / dd.average_trades)
			--processor:notify(str)
			message(str)
		end
		
		str = index:GetMin(dd.min)
		--message(lib:toline(str))
		if str then
			local trade, low, high
			for i = str.first, str.last do
				trade = getItem("all_trades", i)
				if trade and trade.sec_code == dd.sec_code then
					if not low or low > trade.price then low = trade.price end
					if not high or high < trade.price then high = trade.price end
				end
			end
			
			if low and high and high - low > 0 then
				local sl, lm, tp
				if dd.signal_long then
					sl = low
					--lm = high
					lm = (high + low) / 2
					tp = 2 * low - high
				else
					sl = high
					--lm = low
					lm = (high + low) / 2
					tp = 2 * high - low
				end
				
				trade = {sl = sl, lm = lm, tp = tp}
				--message(lib:toline(trade))
				lib:SaveLabels(dd.sec_code, trade)
			end
		end
		
	end
end

